const $ = (s, d = document) => d.querySelector(s);

const rand = (min, max) => Math.random() * (max - min + 1) + min;

const clouds = $(".clouds");
const starsEle = $("#stars");
const count = 20;

clouds.style.setProperty("--count", count);

const frag = document.createDocumentFragment();
for (let i = 0; i < count; i++) {
  const cloud = document.createElement("div");
  cloud.classList.add(`cloud_${i + 1}`);
  frag.appendChild(cloud);
}
clouds.appendChild(frag);

starsEle.width = window.innerWidth;
starsEle.height = window.innerHeight;
const ctx = starsEle.getContext("2d");
let stars = [];

window.addEventListener("resize", () => {
  starsEle.width = window.innerWidth;
  starsEle.height = window.innerHeight;
  makingStar();
});

class Star {
  constructor(x, y, radius, speed) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.speed = speed / 25;
    this.saturation = 95 + this.radius * 5;
    this.lightness = 20 + this.radius * 4;
  }
  update() {
    this.x += this.speed;
    if (this.x - this.radius >= window.innerWidth) {
      this.x = 0;
    }
  }
  render() {
    ctx.beginPath();
    ctx.arc(
      this.x,
      this.y,
      this.radius < 0 ? 0 : this.radius,
      0,
      Math.PI * 2,
      false
    );
    const flickerAdd = rand(0, 140) != 0 ? rand(5, 20) : 0;
    ctx.fillStyle = `hsl(${Math.floor(rand(195, 200))},  ${this.saturation}%, ${
      this.lightness + flickerAdd
    }%)`;
    ctx.fill();
  }
}

function makingStar() {
  stars = [];
  let base = 0.75,
    inc = 0.2,
    count = 40,
    per = 6;
  while (count--) {
    let radius = base + inc,
      perTime = per;
    while (perTime--) {
      radius += inc;
      stars.push(
        new Star(
          rand(0, window.innerWidth - radius),
          rand(0, window.innerHeight - radius),
          radius,
          radius * 3
        )
      );
    }
  }
}

function update() {
  requestAnimationFrame(update);
  updateStars(stars);
  ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
  renderStars(stars);
}

function updateStars(a) {
  let len = a.length;
  while (len--) {
    a[len].update();
  }
}
function renderStars(a) {
  let len = a.length;
  while (len--) {
    a[len].render();
  }
}

makingStar();
update();
